﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ArmoryData.Character;

namespace ArmoryData
{
    public static class Extensions
    {
        /// <summary>
        /// Gets the value of this attribute as an integer
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <returns>The value of the attribute as an integer</returns>
        public static int Int32Value(this XAttribute attribute)
        {
            return int.Parse(attribute.Value);
        }

        /// <summary>
        /// Returns the first descendant of the element with the specified name.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="name">The name.</param>
        /// <returns>
        /// The first descendant of the element with the specified name
        /// </returns>
        public static XElement Descendant(this XElement element, XName name)
        {
            return element.Descendants(name).ElementAt<XElement>(0);
        }

        /// <summary>
        /// Returns the element at the specified index.
        /// </summary>
        /// <param name="elements">The elements.</param>
        /// <param name="index">The index</param>
        /// <returns>The element at the specified index</returns>
        public static XElement ElementAt(this IEnumerable<XElement> elements, int index)
        {
            return elements.ElementAt<XElement>(index);
        }

        /// <summary>
        /// Returns the Glyph with the specified Glyph type and index
        /// </summary>
        /// <param name="glyphs">The glyphs.</param>
        /// <param name="type">The type.</param>
        /// <param name="index">The index</param>
        /// <returns>
        /// THe Glyph with the specified type and index
        /// </returns>
        public static Glyph GetGlyph(this List<Glyph> glyphs, GlyphType type, int index)
        {
            try
            {
                var a = from i in glyphs
                        where i.Type == type
                        select i;
                return a.ElementAt<Glyph>(index);
            }
            catch(ArgumentOutOfRangeException)
            {
                return new Glyph() { Name = null };
            }
        }
    }
}
